package com.fatgirl.interactive.keyboard
{
	import flash.display.Stage;
	import flash.events.KeyboardEvent;

	/**
	 * 
	 * 键盘管理器
	 * @author iceman
	 * 
	 */
	public class KeyboardManager
	{
		private static var s_keyState:Array = new Array;
		private static var s_keyboardObjList:Array = new Array;
		public function KeyboardManager()
		{
		}
		public static function init(_stage:Stage):void
		{
			_stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			_stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
			
		}
		/**
		 * 添加键盘监听的对象 
		 * 重复添加无效
		 * @param _keyBoardObj
		 * @param _keyCode 针对某个keyCode监听，或者默认0 为全部键值监听
		 * 
		 */
		public static function addKeboardObj(_keyBoardObj:IKeyboardObj,_keyCode:uint = 0):void
		{
			if(!_keyBoardObj) return;//不进行添加其他类型
			if(!s_keyboardObjList[_keyCode])s_keyboardObjList[_keyCode] = new Array;
			var t_arr:Array = s_keyboardObjList[_keyCode] as Array;
			if(t_arr) for(var i:int = 0;i<t_arr.length;i++) if(t_arr[i]==_keyBoardObj) return;//不能进行重复添加
			(s_keyboardObjList[_keyCode] as Array).push(_keyBoardObj);
		}
		/**
		 * 移除此对象的键盘事件监听 
		 * @param _keyBoardObj
		 * @param _keyCode
		 * 
		 */
		public static function removeKeboardObj(_keyBoardObj:IKeyboardObj,_keyCode:uint = 0):void
		{
			var t_arr:Array = s_keyboardObjList[_keyCode] as Array;
			if(t_arr)
			{
				for(var i:int = 0;i<t_arr.length;i++)
				{
					if(t_arr[i]==_keyBoardObj)
					{
						t_arr.splice(i,1);
						break;
					}
				}
			}
		}
		/**
		 * 键盘按下设置按键值为true 
		 * @param eve
		 * 
		 */
		private static function onKeyDown(eve:KeyboardEvent):void
		{
			var t_code:uint = eve.keyCode;
			s_keyState[t_code] = true;
			var t_arr:Array = s_keyboardObjList[t_code] as Array;
			if(t_arr && t_code!=0) for(var i:int = 0;i<t_arr.length;i++) (t_arr[i] as IKeyboardObj).onKeyDown(eve);
			var t_arr0:Array = s_keyboardObjList[0];
			if(t_arr0) for(var j:int = 0 ;j<t_arr0.length;j++)(t_arr0[j] as IKeyboardObj).onKeyDown(eve);
			
		}
		/**
		 * 
		 * 键盘弹起设置按键值为true  
		 * @param eve
		 * 
		 */
		private static function onKeyUp(eve:KeyboardEvent):void
		{
			var t_code:uint = eve.keyCode;
			s_keyState[t_code] = false;
			var t_arr:Array = s_keyboardObjList[t_code] as Array;
			if(t_arr && t_code!=0) for(var i:int = 0;i<t_arr.length;i++) (t_arr[i] as IKeyboardObj).onKeyUp(eve);
			var t_arr0:Array = s_keyboardObjList[0];
			if(t_arr0) for(var j:int = 0 ;j<t_arr0.length;j++)(t_arr0[j] as IKeyboardObj).onKeyUp(eve);
		}
		/**
		 * 获取按键当前是否在按下 
		 * @param _keyCode
		 * @return 
		 * 
		 */
		public static function getKeyState(_keyCode:uint):Boolean
		{
			if(s_keyState[_keyCode])return true;
			return false;
		}
		/**
		 * 释放所有按键，设置所有按键值为false 
		 * 
		 */
		public static function freeAllKeyUp():void
		{
			for each (var i:* in s_keyState) i = false;
		}
	}
}